/**
 * Copyright (c) 2008-2016 by DHCC
 * All rights reserved.
 */

package com.dchh.android.suverynew.act;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.dchh.android.suverynew.R;
import com.dchh.android.suverynew.base.SBaseActivity;
import com.dchh.android.suverynew.common.SPreferencesManager;
import com.dchh.android.suverynew.views.SelectPoupWindow;
import com.dhcc.android.base.base.MSApplication;
import com.dhcc.android.base.common.bean.KeyValueBean;
import com.dhcc.android.base.common.view.AlertDialog;
import com.dhcc.android.base.common.view.MyActorPopWindow;
import com.dhcc.android.base.db.DBImportUtil;
import com.dhcc.android.base.db.DBManagerUtil;
import com.dhcc.android.base.db.Sqlite.RecordDBManager;
import com.dhcc.android.base.gis.FactoryGPS;
import com.dhcc.android.base.gis.MultipleItemChangedListener;
import com.dhcc.android.base.gis.TouchLongToolMultiple;
import com.dhcc.android.base.utils.CommenUtil;
import com.dhcc.android.base.utils.Constants;
import com.dhcc.android.base.utils.FileUtil;
import com.dhcc.android.base.utils.StringUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import srs.Display.Symbol.TextSymbol;
import srs.Geometry.Envelope;
import srs.Geometry.FormatConvert;
import srs.Geometry.IEnvelope;
import srs.Geometry.IGeometry;
import srs.Rendering.CommonRenderer;
import srs.Utility.sRSException;
import srs.tools.MapControl;
import srs.tools.ZoomInCommand;
import srs.tools.ZoomOutCommand;

/**
 * 多地块统一填报
 *
 * @author zhoudan
 * @date 2016年5月17日
 */
public class MutiDKReportActivity extends SBaseActivity {


    // 页面组件
    private LinearLayout main;
    /**
     * 层级目录
     */
    private TextView title;//
    /**
     * 层级选择目录布局
     */
    private LinearLayout titleLayout;

    private RelativeLayout reportBtn;
    /**
     * 指南针
     */
    private LinearLayout zhinanzhen;
    /**
     * 任务名称
     */
    private String taskName;

    // 选择列表的数据
    /**
     * 原始数据
     */
    private List<Map<String, String>> dataList = null;
    /**
     * 数据库管理工具
     */
    public static DBManagerUtil dBManagerUtil;
    /**
     * 样方编号主键
     */
    public static String YFBHU = "";
    public static String dbPath;
    /**
     * 任务包路径
     */
    public static String root;
    /**
     * 路径
     */
    private String navtitle;

    private String demandPath;
    private String periodLabel;

    //地图
    private MapControl dkSelectMapControl;
    private TextView tv_GPSInfo = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dk_muti_report);
    }

    //===========地图处理===========

    private void mapView() {
        List<Map<String, String>> entityList = dataList;
        Constants.displayLableNames.clear();
        Constants.displayRenderBreaks.clear();
        if (entityList != null && entityList.size() != 0) {// 查出为[{GEO=null},{GEO=null}]
            boolean isFirst = true;
            try {
                for (Map<String, String> map : entityList) {
                    String wkt = map.get("GEO");

                    if (StringUtil.isNotEmpty(wkt)) {
                        IGeometry geo = FormatConvert.WKTToPolygon(wkt);
                        if (geo != null) {
                            if (isFirst) {// 有数据后 第一次进来的时候 将清空
                                isFirst = false;
                                Constants.geometrys.clear();
                            }
                            Constants.geometrys.add(geo);
                        }
                    }
                    String LableID = "";
                    LableID = map.get("YFDKBH");

                    if (LableID != null) {
                        Constants.displayLableNames.add(LableID);
                    }

                    String breaks = map.get("COMPLETE");
                    double breakValue = 0;
                    breakValue = Double.valueOf(breaks);
                    Constants.displayRenderBreaks.add(breakValue);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Constants.COMMONLAYER.setLabelSymbol(new TextSymbol(Typeface.create("Times New Roman", Typeface.NORMAL), 0,
                12f, false, Color.BLACK));

        //-----设置为分段渲染
        Constants.RENDERCBJ.AddBreak(0, "未填报", Constants.SYMBOLCBJ, null);
        Constants.RENDERCBJ.AddBreak(1, "已填报", Constants.SYMBOLCBJWC, null);
        try {
            Constants.COMMONLAYER.setRenderer(Constants.RENDERCBJ);
        } catch (sRSException e) {
            ((CommonRenderer) Constants.COMMONLAYER.getRenderer()).setSymbol(Constants.SYMBOLCBJ);
            System.out.println("地块图层分段渲染有误！");
            e.printStackTrace();
        }
        //-----设置分段渲染完毕

        Constants.COMMONLAYER.setInitInfos("TableName", Constants.geometrys, Constants.displayRenderBreaks,
                srs.Geometry.srsGeometryType.Polygon, Constants.displayLableNames, new Envelope(), null);

        // 地图控件
        IEnvelope env = CommenUtil.getMap().getExtent();
        dkSelectMapControl = (MapControl) findViewById(R.id.mapmain);

        dkSelectMapControl.getActiveView().FocusMap(CommenUtil.getMap());
        CommenUtil.getMap().setExtent(env);

        CommenUtil.getMap().setDeviceExtent(
                new Envelope(0, 0, dkSelectMapControl.getWidth(), dkSelectMapControl.getHeight()));
        // 刷新图层
        dkSelectMapControl.Refresh();

        /** 增加地图点选事件 */
        /** CommenLayer的多选事件 */
        TouchLongToolMultiple toolMultiple = new TouchLongToolMultiple(Constants.COMMONLAYER);
        dkSelectMapControl.ClearDrawTool();
        toolMultiple.setBuddyControl(dkSelectMapControl);// mapControl为操作的地图控件
        toolMultiple.onClick(dkSelectMapControl);
        toolMultiple.setEnable(true);
        // 设置不累计选择项目
        toolMultiple.IsOnlyOneTime = true;
        // 设置是不为单选
        toolMultiple.IsOnlyOneSelect = true;
        // 设置选中或未选中条目时，触发的事件
        toolMultiple.zoom2Selected = new MultipleItemChangedListener() {

            @Override
            public void doEventSettingsChanged(List<Integer> indexs) {
                // TODO Auto-generated method stub
                // 返回一个下标结合list
                dkIndexs = indexs;
            }
        };
        dkSelectMapControl.setDrawTool(toolMultiple);
    }

    private void mapRefresh() {
        // 计算geometrys
        List<Map<String, String>> entityList = dataList;
        Constants.displayLableNames.clear();
        Constants.displayRenderBreaks.clear();
        if (entityList != null && entityList.size() != 0) {// 查出为[{GEO=null},{GEO=null}]
            boolean isFirst = true;
            try {
                for (Map<String, String> map : entityList) {
                    String wkt = map.get("GEO");

                    if (StringUtil.isNotEmpty(wkt)) {
                        IGeometry geo = FormatConvert.WKTToPolygon(wkt);
                        if (geo != null) {
                            if (isFirst) {// 有数据后 第一次进来的时候 将清空
                                isFirst = false;
                                Constants.geometrys.clear();
                            }
                            Constants.geometrys.add(geo);
                        }
                    }
                    String LableID = "";
                    LableID = map.get("YFDKBH");

                    if (LableID != null) {
                        Constants.displayLableNames.add(LableID);
                    }

                    String breaks = map.get("COMPLETE");
                    double breakValue = 0;
                    breakValue = Double.valueOf(breaks);
                    Constants.displayRenderBreaks.add(breakValue);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Constants.COMMONLAYER.setLabelSymbol(new TextSymbol(Typeface.create("Times New Roman", Typeface.NORMAL), 0,
                12f, false, Color.BLACK));

        //-----设置为分段渲染
        Constants.RENDERCBJ.AddBreak(0, "未填报", Constants.SYMBOLCBJ, null);
        Constants.RENDERCBJ.AddBreak(1, "已填报", Constants.SYMBOLCBJWC, null);
        try {
            Constants.COMMONLAYER.setRenderer(Constants.RENDERCBJ);
        } catch (sRSException e) {
            ((CommonRenderer) Constants.COMMONLAYER.getRenderer()).setSymbol(Constants.SYMBOLCBJ);
            System.out.println("地块图层分段渲染有误！");
            e.printStackTrace();
        }
        //-----设置分段渲染完毕

        Constants.COMMONLAYER.setInitInfos("TableName", Constants.geometrys, Constants.displayRenderBreaks,
                srs.Geometry.srsGeometryType.Polygon, Constants.displayLableNames, new Envelope(), null);

        dkSelectMapControl.Refresh();
    }

    private void configMap(Context context) {

        // add 杨宗仁 定位，放大，缩小按钮
        LayoutParams sp_params1 = new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        LayoutParams sp_params2 = new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        LayoutParams sp_params3 = new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        ImageView btnZoomin = new ImageView(context);
        ImageView btnZoomout = new ImageView(context);
        ImageView ivLocationCenter = new ImageView(context);
        btnZoomin.setImageResource(R.mipmap.zoom_in);
        btnZoomout.setImageResource(R.mipmap.zoom_out);
        ivLocationCenter.setImageResource(R.mipmap.gps_recieved);

        btnZoomin.setBackgroundResource(R.drawable.duidi_bt_clickerstyle2);
        btnZoomout.setBackgroundResource(R.drawable.duidi_bt_clickerstyle2);
        ivLocationCenter
                .setBackgroundResource(R.drawable.duidi_bt_clickerstyle2);

        sp_params1.width = Constants.screenWidth / 11;
        sp_params1.height = Constants.screenWidth / 11;
        sp_params1.bottomMargin = Constants.screenWidth / 11 + 32;
        sp_params1.rightMargin = 16;
        sp_params1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        sp_params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

        btnZoomin.setLayoutParams(sp_params1);

        sp_params2.width = Constants.screenWidth / 11;
        sp_params2.height = Constants.screenWidth / 11;
        sp_params2.rightMargin = 16;
        sp_params2.bottomMargin = 16;
        sp_params2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        sp_params2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        btnZoomout.setLayoutParams(sp_params2);

        sp_params3.width = Constants.screenWidth / 11;
        sp_params3.height = Constants.screenWidth / 11;
        sp_params3.leftMargin = 16;
        sp_params3.bottomMargin = 30;
        sp_params3.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        sp_params3.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        ivLocationCenter.setLayoutParams(sp_params3);

        dkSelectMapControl.setGravity(Gravity.BOTTOM);

        dkSelectMapControl.addView(btnZoomin);
        dkSelectMapControl.addView(btnZoomout);
        dkSelectMapControl.addView(ivLocationCenter);
        if (btnZoomin != null) {
            btnZoomin.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            ZoomInCommand zoomin = new ZoomInCommand();
                            zoomin.setBuddyControl(dkSelectMapControl);
                            zoomin.setEnable(true);
                            zoomin.onClick(v);
                    }
                    return true;
                }
            });
        }
        if (btnZoomout != null) {
            btnZoomout.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            ZoomOutCommand zoomout = new ZoomOutCommand();
                            zoomout.setBuddyControl(dkSelectMapControl);
                            zoomout.setEnable(true);
                            zoomout.onClick(v);
                    }
                    return true;
                }
            });
        }

        if (ivLocationCenter != null) {
            ivLocationCenter.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View arg0, MotionEvent arg1) {
                    CommenUtil.SetLocationCenter(dkSelectMapControl);
                    return true;
                }
            });
        }

        if (tv_GPSInfo == null) {
            tv_GPSInfo = new TextView(this);
        }
        tv_GPSInfo.setTextColor(Color.BLACK);
        tv_GPSInfo.setBackgroundColor(Color.argb(128, 255, 255, 255));

        dkSelectMapControl.addView(tv_GPSInfo,
                LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);

        try {

            FactoryGPS factory = new FactoryGPS(tv_GPSInfo, null, null, null,
                    CommenUtil.getMapControl());
            FactoryGPS.NaviStart = false;
            factory.StartStopGPS(this, tv_GPSInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void getView() {
        getData();
        // 获取视图组件
        title = (TextView) findViewById(R.id.common_title);
        title.setText(navtitle);
        titleLayout = (LinearLayout) findViewById(R.id.common_nav);

        zhinanzhen = (LinearLayout) findViewById(R.id.zhinanzhen_operate);
        zhinanzhen.setVisibility(View.VISIBLE);
        zhinanzhen.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MutiDKReportActivity.this, CompassActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
            }
        });
    }


    private void getData() {
        String pfield = "YFBHU";
        // 获取数据库中当前层级的下级数据列表
        String[] fields = {"COMPLETE", "DKBHU", "YFDKBH", "YFBHU", "TBMJ", "rowid", "GEO"};
        try {
            DBImportUtil.openDatabase(root, taskName, "/TASK/TRANSPORT/DATA.db");
            String tablename = CommenUtil.getTableName("样方自然地块", periodLabel);
            if (YFBHU == null) {
                dataList = DBImportUtil.listData(tablename, fields, null, null);
            } else {
                dataList = DBImportUtil.listData(tablename, fields, pfield, YFBHU);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "操作外部数据库出错", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    protected void setTitle(TextView toolbar_title) {

    }

    @Override
    protected void initView() {
        root = SPreferencesManager.getValue(MSApplication.TASK_SAVE_PATH, FileUtil.getSavePath());
        YFBHU = getIntent().getStringExtra("YFBHU");
        navtitle = getIntent().getStringExtra("navtitle");
        taskName = getIntent().getStringExtra("taskName");
        dbPath = root + "/" + taskName + "/TASK/TRANSPORT/DATA.db";
        demandPath = root + "/" + taskName + "/DEMAND/DEMAND.db";
        dBManagerUtil = DBManagerUtil.getInstance(dbPath, this);
        periodLabel = Constants.getTempData(MutiDKReportActivity.this, MSApplication.PERIOD_LABEL);
        String title = getIntent().getStringExtra("title");
        setTitle(title);
        getView();
        getForm();
        mapView();
        configMap(this);
    }

    //===================单一作物统一保存=========================
    public final static String SSNYYDLX = "设施农业用地类型";
    public final static String ZZYSSYD = "种植业设施用地";

    //填报表单
    private LinearLayout reportMain;
    private LinearLayout dwflLayout, fzcsLayout;
    private TextView tblx, ejfl, dwfl;
    private EditText fzcs;
    private LinearLayout add1, add2, add3;
    private LinearLayout cancle;
    private LinearLayout ok;

    /**
     * 地图点选后获得的地块索引集合
     */
    private List<Integer> dkIndexs = new ArrayList<Integer>();
    /**
     * 选择的地块 详细信息集合
     */
    private List<Map<String, String>> dkList = new ArrayList<Map<String, String>>();

    /**
     * 图斑类型--值
     */
    private KeyValueBean TBLX;
    /**
     * 图斑类型数据集合
     */
    private List<KeyValueBean> tblxList;
    /**
     * 设施农业用地类型数据集合
     */
    private List<String> sslxList;
    /**
     * 设施农业用地类型-值
     */
    private String sslx;
    /**
     * 作物
     */
    private List<Map<String, String>> zwmap = new ArrayList<Map<String, String>>();
    /**
     * 复种次数
     */
    private String FZCS;

    /**
     * 初始填报表单
     */
    private void getForm() {
        //==============填报表单=====================
        reportMain = (LinearLayout) findViewById(R.id.muti_report);

        dwflLayout = (LinearLayout) findViewById(R.id.dwfl_layout);
        fzcsLayout = (LinearLayout) findViewById(R.id.fzcs_layout);

        tblx = (TextView) findViewById(R.id.tblx);
        ejfl = (TextView) findViewById(R.id.ejfl);
        dwfl = (TextView) findViewById(R.id.dwfl);
        fzcs = (EditText) findViewById(R.id.fzcs);

        add1 = (LinearLayout) findViewById(R.id.add1);
        add2 = (LinearLayout) findViewById(R.id.add2);
        add3 = (LinearLayout) findViewById(R.id.add3);

        cancle = (LinearLayout) findViewById(R.id.poup_cancle);
        ok = (LinearLayout) findViewById(R.id.poup_ok);

        cancle.setOnClickListener(formClick);
        ok.setOnClickListener(formClick);
        add1.setOnClickListener(formClick);
        add2.setOnClickListener(formClick);
        add3.setOnClickListener(formClick);

        fzcs.addTextChangedListener(textChange);
    }

    /**
     * 根据选择索引获取地块详情
     */
    private void getDKINFOLIST() {
        dkList.clear();
        for (int index : dkIndexs) {
            dkList.add(dataList.get(index));
        }
    }

    /**
     * 复位
     */
    private void clearAll() {
        setTBLX(null);
        clearEJFL();
        setDWFL(null);
        setFZCS(null);

        showSSNY(View.GONE);

        reportMain.setVisibility(View.GONE);
    }

    /**
     * 设置图斑类型
     */
    private void setTBLX(KeyValueBean kv) {
        TBLX = kv;
        if (kv != null) {
            tblx.setText(kv.getValue());
        } else {
            tblx.setText("");
        }
    }

    /**
     * 清除 二级分类
     */
    private void clearEJFL() {
        zwmap.clear();
        sslx = "";

        ejfl.setText("");
    }

    /**
     * 设置 作物
     */
    private void setZWFL(Map<String, String> map) {
        zwmap.clear();

        if (map != null) {
            zwmap.add(map);
            ejfl.setText(map.get("ZWMC"));
        } else {
            ejfl.setText("");
        }
    }

    /**
     * 设置 设施用地类型  二级
     */
    private void setEJFL(String s) {
        sslx = s;
        if (s != null) {
            ejfl.setText(s);
        } else {
            ejfl.setText("");
        }
    }

    /**
     * 设置 设施农业地物分类
     */
    private void setDWFL(Map<String, String> map) {
        zwmap.clear();

        if (map != null) {
            zwmap.add(map);
            dwfl.setText(map.get("SNZWMC"));
        } else {
            dwfl.setText("");
        }
    }

    /**
     * 设置复种次数
     */
    private void setFZCS(String s) {
        FZCS = s;
        if (s != null) {
            fzcs.setText(s);
        } else {
            fzcs.setText("");
        }
    }

    /**
     * 设置 设施农业 填报 可见性
     */
    private void showSSNY(int visible) {
        dwflLayout.setVisibility(visible);
        fzcsLayout.setVisibility(visible);
    }


    /**
     * 获取图斑类型列表
     */
    private List<KeyValueBean> getTblxList() {
        List<KeyValueBean> list = dBManagerUtil.getListDatas("DIC_TBLX", new KeyValueBean("PID", "VALUE"), null, demandPath);

        return list;
    }

    /**
     * 获取设施农业用地类型列表
     */
    private List<String> getSSLXList() {
        List<String> list = dBManagerUtil.getListDatas("DIC_ZW", "VALUE", "CLASSIFICATION='设施农业用地类型（900）'", demandPath);

        return list;
    }

    private List<KeyValueBean> zwlist;

    /**
     * 显示作物选择列表
     *
     * @param type   是不是 设施农业用地类型  0-不是， 1-是
     * @param parent
     * @param key    作物ID字段名
     * @param value  作物名称字段名
     * @param filter 作物数据过滤条件
     */
    private void showZWSELECT(final int type, View parent, String key, String value, String filter) {
        if (zwlist == null || zwlist.size() == 0) {
            zwlist = dBManagerUtil.getZWDatas("DIC_ZW", new KeyValueBean("PID", "VALUE", "CLASSIFICATION"), filter, demandPath);
        }

        MyActorPopWindow pw = new MyActorPopWindow(this, parent, new MyActorPopWindow.OnSelectListener() {

            @Override
            public void onSelect(List<Map<String, String>> results) {
            }

            @Override
            public void OnSingleSelect(Map<String, String> map) {
                if (type == 0) {//不是 设施农业用地类型
                    setZWFL(map);
                } else {
                    setDWFL(map);
                }
            }

        });
        pw.show(zwlist, zwmap, new KeyValueBean(key, value), true);

    }


    OnClickListener formClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.poup_cancle:
                    clearAll();
                    break;
                case R.id.poup_ok:
                    check();
                    break;
                case R.id.add1: //图斑类型选择
                    if (tblxList == null || tblxList.size() == 0) {
                        tblxList = getTblxList();
                    }
                    SelectPoupWindow selectpopup = new SelectPoupWindow(MutiDKReportActivity.this);
                    selectpopup.show(v, new SelectPoupWindow.OnSelectListener() {

                        @Override
                        public void onSelectString(View view, String value) {
                        }

                        @Override
                        public void onSelectKeyValueBean(View view, KeyValueBean kv) {
                            setTBLX(kv);
                            clearEJFL();
                            setDWFL(null);
                            setFZCS(null);

                            if (zwlist != null) {
                                zwlist.clear();
                            }

                            if (kv.getValue().equals(SSNYYDLX)) {
                                showSSNY(View.VISIBLE);
                            } else {
                                showSSNY(View.GONE);
                            }
                        }
                    }, null, tblxList);
                    break;
                case R.id.add2://二级分类
                    if (TBLX.getValue().equals(SSNYYDLX)) {
                        if (sslxList == null || sslxList.size() == 0) {
                            sslxList = getSSLXList();
                        }
                        selectpopup = new SelectPoupWindow(MutiDKReportActivity.this);
                        selectpopup.show(v, new SelectPoupWindow.OnSelectListener() {

                            @Override
                            public void onSelectString(View view, String value) {
                                setEJFL(value);
                                setDWFL(null);
                                setFZCS(null);
                            }

                            @Override
                            public void onSelectKeyValueBean(View view, KeyValueBean kv) {
                            }

                        }, sslxList);
                    } else {
                        showZWSELECT(0, v, "ZWBH", "ZWMC", "CLASSIFICATION='" + TBLX.getValue() + "（" + TBLX.getKey() + "）'");
                    }
                    break;
                case R.id.add3://设施地物
                    showZWSELECT(1, v, "SNZWBH", "SNZWMC", "CLASSIFICATION !='设施农业用地类型（900）'");
                    break;

                default:
                    break;
            }
        }
    };


    TextWatcher textChange = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            String v = s.toString().trim();
            FZCS = v;
        }
    };


    private void check() {
        //图标类型不能为空
        if (TBLX == null) {
            CommenUtil.toast("请先选择 图标类型", this);
        } else {
            String ej = ejfl.getText().toString();
            //二级分类不能为空
            if (ej == null || ej.equals("")) {
                CommenUtil.toast("请先选择 二级分类", this);
            } else {
                if (TBLX.getValue().equals(SSNYYDLX)) {//设施农业用地类型
                    if (sslx.equals(ZZYSSYD)) {//种植业设施用地
                        if (zwmap.size() == 0) {
                            CommenUtil.toast("请先选择 地物分类", this);
                        } else {
                            //保存
                            alert(2, CommenUtil.getTableName("设施", periodLabel), CommenUtil.getDCQ(periodLabel));
                        }
                    } else {//不是 种植业设施用地
                        //如果 作物 为空  复种次数不为空  不允许保存
                        if (StringUtil.isNotEmpty(FZCS) && zwmap.size() == 0) {
                            CommenUtil.toast("请先选择 地物分类", this);
                        } else {
                            if (zwmap.size() == 0) {
                                //保存一条空数据
                                alert(0, CommenUtil.getTableName("设施", periodLabel), CommenUtil.getDCQ(periodLabel));
                            } else {
                                //保存
                                alert(2, CommenUtil.getTableName("设施", periodLabel), CommenUtil.getDCQ(periodLabel));
                            }
                        }
                    }
                } else {//作物
                    //保存
                    alert(1, CommenUtil.getTableName("作物", periodLabel), CommenUtil.getDCQ(periodLabel));
                }
            }
        }
    }

    /**
     * 弹窗
     *
     * @param type  0-空数据   1-作物    2-设施
     * @param table
     * @param dcq
     */
    private void alert(final int type, final String table, final String dcq) {
        final AlertDialog alertDialog = new AlertDialog(this, "若选中地块存在调查数据，本操作将覆盖已有数据，确定保存？", "确定", "取消");
        alertDialog.show();
        alertDialog.setClicklistener(new AlertDialog.ClickListenerInterface() {

            @Override
            public void doConfirm() {
                alertDialog.dismiss();
                if (type == 0) {//空数据
                    dBManagerUtil.add(table, dbPath, dcq, dkList, null, TBLX, sslx, FZCS);
                } else if (type == 1) {//作物
                    dBManagerUtil.add(table, dbPath, dcq, dkList, zwmap.get(0), TBLX, null, null);
                } else if (type == 2) {//设施
                    dBManagerUtil.add(table, dbPath, dcq, dkList, zwmap.get(0), TBLX, sslx, FZCS);
                }
                clearAll();
                CommenUtil.toast("保存成功", MutiDKReportActivity.this);

                //保存 进度记录
                RecordDBManager db = new RecordDBManager(MutiDKReportActivity.this);
                db.add(dkList, "4", "003");

                Constants.data_refresh = true;
                getData();
                mapRefresh();
            }

            @Override
            public void doCancel() {
                alertDialog.dismiss();
            }

        });

    }
}
